package com.freedom.rpc.thrift.registry;


import java.util.HashMap;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.freedom.rpc.thrift.common.utils.LoggerUtils;
import com.freedom.rpc.thrift.server.utils.MyServerProperties;

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisPoolManager {
	//
	// 私有成员
	private JedisPoolManager() {
	}

	private HashMap<String, JedisPool> jedisPools = new HashMap<String, JedisPool>();

	public JedisPool getJedisPools(String address) {
		return jedisPools.get(address);
	}

	private void addJedisPool(String address, JedisPool pool) {
		jedisPools.put(address, pool);
	}

	//
	// 下面是静态类
	private static final Logger logger = LogManager.getLogger(JedisPoolManager.class);
	private static JedisPoolManager instance = null;

	public static JedisPoolManager getInstance() {
		return instance;
	}

	static {
		// 参考文档:
		// http://www.cnblogs.com/tankaixiong/p/4048167.html
		// http://blog.csdn.net/songylwq/article/details/26008327
		LoggerUtils.info(logger, "begin to init jedis pool...");
		// 初始化instance
		instance = new JedisPoolManager();
		// 准备好配置
		JedisPoolConfig config = new JedisPoolConfig();
		// config.setFairness(fairness);
		config.setMaxIdle(6);
		config.setMinIdle(2);
		config.setMaxTotal(10);
		config.setLifo(false);
		// 有效性校验
		config.setTestOnBorrow(true);
		config.setTestOnCreate(true);
		config.setTestOnReturn(true);
		config.setTestWhileIdle(true);
		// 设置获取资源的等待时长
		config.setBlockWhenExhausted(true);
		config.setMaxWaitMillis(3000);// 等待3秒

		// 逐出扫描
		config.setTimeBetweenEvictionRunsMillis(6000);// 逐出扫描的时间间隔
		config.setMinEvictableIdleTimeMillis(1 * 60 * 1000);// 1分钟
		config.setSoftMinEvictableIdleTimeMillis(1 * 60 * 1000);// 1分钟
		config.setNumTestsPerEvictionRun(6);// 每次逐出的最大数量
		// config.setEvictionPolicyClassName(evictionPolicyClassName);
		//
		String[] redisServers = MyServerProperties.getInstance().getRedisServers();
		for (String redisServer : redisServers) {
			redisServer = redisServer.trim();
			String[] ipPort = redisServer.split(":");
			JedisPool pool = new JedisPool(config, ipPort[0], Integer.parseInt(ipPort[1]));
			instance.addJedisPool(redisServer, pool);
		}
		LoggerUtils.info(logger, "end to init jedis pool,bingo...");
	}

}
